﻿using System;
using System.Windows;
using System.Windows.Controls;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;

namespace FAQ_UI
{
	/// <summary>
	/// SelectServer.xaml 的交互逻辑
	/// </summary>
	public partial class SelectServer : Page, MsgPackReceiver
	{
		public SelectServer()
		{
			InitializeComponent();
			DataContext = this;
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.client.removeReceiver(this);
			//FAQUtil.eventBus.removeReceiver(this);
		}

		public string serverAddress
		{
			get
			{
				return FAQUtil.settings.getString(D.SETTINGS, "ServerAddress") + "";
			}
			set
			{
				FAQUtil.settings.put(D.SETTINGS, "ServerAddress", value);
				FAQUtil.settings.delaySave(1000);
			}
		}

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			int cmd = mp.getCmd();
			if (cmd == C.LOGIN)
			{
				FAQUtil.client.removeReceiver(this);
				Dispatcher.Invoke(new Action(() => { connectButton.IsEnabled = true; }));
			}
			else if (cmd == C.SESSION_STOPPED)
			{
				FAQUtil.client.removeReceiver(this);
				Dispatcher.Invoke(new Action(() => { connectButton.IsEnabled = true; }));
			}
		}

		private void connectServer(object sender, RoutedEventArgs e)
		{
			FAQUtil.client.addReceiver(this);
			FAQUtil.client.closeConnections();
			FAQUtil.client.connectTo(serverAddress);
			connectButton.IsEnabled = false;
		}
	}
}